package com.bawei.shoppingcar;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.bawei.shoppingcar.entity.LoginEntity;
import com.bawei.shoppingcar.entity.RegisterEntity;
import com.bawei.shoppingcar.utils.HttpUtils;
import com.google.gson.Gson;

public class RegisterActivity extends AppCompatActivity {
    private EditText etUsername;
    private EditText etRepassword;
    private EditText etPassword;
    private Button btRegister;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        etUsername = (EditText) findViewById(R.id.et_username);
        etRepassword = (EditText) findViewById(R.id.et_repassword);
        btRegister = (Button) findViewById(R.id.bt_register);
        etPassword = (EditText) findViewById(R.id.et_password);
        btRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = etUsername.getText().toString();
                String password = etPassword.getText().toString();
                String repassword = etRepassword.getText().toString();
                //请求参数
                String params = "username="+username+"&password="+password+"&repassword="+repassword;
                new RegisterTask().execute("http://43.143.146.165:8083/user/register",params);
            }
        });


    }
    //注册线程
    class RegisterTask extends AsyncTask<String,Void,String> {
        @Override
        protected String doInBackground(String... strings) {
            return HttpUtils.doPost(strings[0],strings[1]);
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            RegisterEntity registerEntity = new Gson().fromJson(s, RegisterEntity.class);
            if(registerEntity != null && registerEntity.getCode() == 200){
                Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                //将数据回传值给登陆页面
                Bundle bundle = new Bundle();
                bundle.putString("username",registerEntity.getData().getUsername());
                bundle.putString("password",registerEntity.getData().getPassword());
                Intent intent = new Intent();
                intent.putExtras(bundle);
                setResult(102,intent);
                finish();
            }else{
                Toast.makeText(RegisterActivity.this, "注册失败"+registerEntity.getMessage(), Toast.LENGTH_SHORT).show();
            }


        }
    }
}